﻿using G3WebERPApi.Common;
using G3WebERPApi.Model;
using Newtonsoft.Json;

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace G3WebERPApi.Approval
{
    /// <summary>
    /// 获取流程类型
    /// </summary>
    public class GetBillName : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            //判断客户端请求是否为post方法
            if (context.Request.HttpMethod.ToUpper() != "POST")
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "请使用POST方式" }));
                return;
            }

            try
            {
                string signUrl = ToolsClass.GetConfig("signUrl"); context.Response.ContentType = "text/plain";
                string CsJson;
                //获取请求json
                using (var reader = new StreamReader(context.Request.InputStream, Encoding.UTF8))
                {
                    CsJson = reader.ReadToEnd();
                }

                if (CsJson == "")
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "报文格式错误" }));
                    return;
                }
                CsJson = Regex.Replace(CsJson, @"[\n\r]", "").Replace(@"\n", ",").Replace("'", "‘").Replace(@"\t", ":").Replace(@"\r", ",").Replace(@"\n", ",");
                //json转Hashtable
                object jgobj = ToolsClass.DeserializeObject(CsJson);
                if (!(jgobj is Hashtable returnhash))
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "报文格式错误" }));
                    return;
                }

                string path = context.Request.Path.Replace("Approval/GetBillName.ashx", "billname");
                string path1 = context.Request.Path.Replace("Approval/GetBillName.ashx", "getbillclassnode");
                //验证请求sign
                string sign = ToolsClass.md5(signUrl + path + "Romens1/DingDing2" + path, 32);
                string sign1 = ToolsClass.md5(signUrl + path1 + "Romens1/DingDing2" + path1, 32);
                ToolsClass.TxtLog("生成的sign", "生成的" + sign + "传入的sign" + returnhash["Sign"].ToString() + "\r\n 后台字符串:" + signUrl + path + "Romens1/DingDing2" + path);
                if (sign != returnhash["Sign"].ToString() && sign1 != returnhash["Sign"].ToString())
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "认证信息Sign不存在或者不正确" }));
                    return;
                }
                string SearchAall = string.Empty;
                if (returnhash.Contains("SearchAall"))
                {
                    SearchAall = returnhash["SearchAall"].ToString();
                    if (SearchAall == "")
                    {
                        context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "SearchAall不允许为空" }));
                        return;
                    }
                }

                //#微应用ID:agentId #企业ID:corpId #应用的唯一标识:appKey #应用的密钥:appSecret
               var AppWyy = ToolsClass.GetConfig("AppWyy");
               var ScList = AppWyy.Split('$');
                var agentId = ScList[0];
                var corpId = ScList[1];
                var appKey = ScList[2];
                var appSecret = ScList[3];
                
              string  ddUrl = ToolsClass.GetConfig("ddUrl");

                
                    ToolsClass.TxtLog("获取审批类型日志", "\r\n获取审批类型信息入参:" + CsJson.ToString() + "\r\n");


                //获取access_token
                string url = "https://oapi.dingtalk.com/gettoken?appkey=" + appKey + "&appsecret=" + appSecret;
                string FhJson = ToolsClass.ApiFun("GET", url, "");

                CommonModel tokenClass = new CommonModel();
                tokenClass = (CommonModel)JsonConvert.DeserializeObject(FhJson, typeof(CommonModel));
                string access_token = tokenClass.access_token;
                
                if (tokenClass.errcode != "0")
                {
                    context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "获取ACCESS_TOKEN报错" }));
                    return;
                }
                string sql = string.Empty;
                string result = string.Empty;
                //获取流程类型
                if (SearchAall == "1")
                {
                    sql = "select BillClassid,BillName,BillLogoUrl,BillUrl,VisibleRange from BillClass";
                    var dt = StaticDbHelper.GetSqlHelper().GetDataTable(sql);
                    if (dt.Rows.Count !=0)
                    {
                        List<BillInfo> billInfos = new List<BillInfo>();
                        for (int i = 0; i < dt.Rows.Count; i++)
                        {
                            billInfos.Add(new BillInfo { 
                                BillClassid = dt.Rows[i].DataRowGetStringValue("BillClassid"),
                                BillLogoUrl = dt.Rows[i].DataRowGetStringValue("BillLogoUrl"),
                                BillName = dt.Rows[i].DataRowGetStringValue("BillName"),
                                BillUrl = dt.Rows[i].DataRowGetStringValue("BillUrl"),
                                VisibleRange = dt.Rows[i].DataRowGetStringValue("VisibleRange")
                            });
                        }

                        result = JsonConvert.SerializeObject(new GetBillInfoModel
                        {
                            errcode = 0,
                            count = dt.Rows.Count,
                            data = billInfos,
                            errmsg = ""
                        });
                    }
                    else
                    {
                        result = JsonConvert.SerializeObject(new GetBillInfoModel
                        {
                            errcode = 0,
                            count = dt.Rows.Count,
                            errmsg = ""
                        });
                    }

                    
                }
                string ClassType = string.Empty;
                //获取现在已保存的流程信息节点
                if (SearchAall == "2")
                {
                    ClassType = returnhash["ClassType"].ToString();
                    if (ClassType == "")
                    {
                        context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "ClassType不允许为空" }));
                        return;
                    }
                    sql = $"select ClassRuCan from BillClass where BillClassid ='{ClassType}' ";
                    result = StaticDbHelper.GetSqlHelper().GetValue(sql).ToString();
                }
                context.Response.Write(result.Replace(" ", ""));
               
                    ToolsClass.TxtLog("获取审批类型日志", "\r\n获取审批类型信息出参:" + result + "\r\n");
               
                return;
            }
            catch (Exception ex)
            {
                context.Response.Write(JsonConvert.SerializeObject(new CommonModel { errcode = "-1", errmsg = "获取billname发生异常" }));
                ToolsClass.TxtLog("获取审批类型日志", $"\r\n{JsonConvert.SerializeObject(ex)}\r\n");
                return;
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}